package com.toolkit.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * zip生成工具类
 * @author Administrator
 * @date 2017年7月12日
 */
public class ZipUtil {
    public static void zip(String inputFileName,String zipFileName) throws Exception {
        zip(zipFileName, new File(inputFileName));
    }

    private static void zip(String zipFileName, File inputFile) throws Exception {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
        zip(out, inputFile, inputFile.getName());
        out.close();
    }

    private static void zip(ZipOutputStream out, File f, String base) throws Exception {
        if (f.isDirectory()) {
            File[] fl = f.listFiles();
            if(fl!=null && fl.length>0){
                out.putNextEntry(new ZipEntry(base + "/"));
                base = base.length() == 0 ? "" : base + "/";
                for (int i = 0; i < fl.length; i++) {
                    zip(out, fl[i], base + fl[i].getName());
                }
            }
        }else{
            out.putNextEntry(new ZipEntry(base));
            FileInputStream in = new FileInputStream(f);
            int b;
            //System.out.println(base);
            while ( (b = in.read()) != -1) {
                out.write(b);
            }
            in.close();
        }
    }

    public static void main(String [] temp){
        try {
            ZipUtil.zip("f:\\test","f:\\test.zip");//你要压缩的文件夹       压缩到的位置和文件名
        }catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
